<template>
  <div class="app-container">
    <el-tabs tab-position="left">
      <!-- 基本设置 Tab Pane -->
      <el-tab-pane label="账号信息">
        <div class="w-full">
          <el-card>
            <!-- 头像和昵称部分 -->
            <div class="relative w-100px h-100px flex-center">
              <el-avatar :src="userProfile.avatar" :size="100" />
              <el-button type="info" class="absolute bottom-0 right-0 cursor-pointer" circle :icon="Camera" size="small"
                @click="triggerFileUpload" />
              <input ref="fileInput" type="file" style="display: none" @change="handleFileChange" />
            </div>
            <div class="mt-5">
              {{ userProfile.nickname }}
              <el-icon class="align-middle cursor-pointer" @click="handleOpenDialog(DialogType.ACCOUNT)">
                <Edit />
              </el-icon>
            </div>
            <!-- 用户信息描述 -->
            <el-descriptions :column="1" class="mt-10">
              <!-- 用户名 -->
              <el-descriptions-item>
                <template #label>
                  <el-icon class="align-middle">
                    <User />
                  </el-icon>
                  用户名
                </template>
                {{ userProfile.username }}
                <el-icon v-if="userProfile.gender === 1" class="align-middle color-blue">
                  <Male />
                </el-icon>
                <el-icon v-else class="align-middle color-pink">
                  <Female />
                </el-icon>
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <el-icon class="align-middle">
                    <Phone />
                  </el-icon>
                  手机号码
                </template>
                {{ userProfile.mobile }}
              </el-descriptions-item>
              <el-descriptions-item>
                <template #label>
                  <el-icon class="align-middle">
                    <Message />
                  </el-icon>
                  邮箱
                </template>
                {{ userProfile.email }}
              </el-descriptions-item>
              <!-- <el-descriptions-item>
                <template #label>
                  <div class="i-svg:tree" />
                  部门
                </template>
                {{ userProfile.deptName }}
              </el-descriptions-item> -->
              <el-descriptions-item>
                <template #label>
                  <div class="i-svg:role" />
                  角色
                </template>
                {{ userProfile.roleNames }}
              </el-descriptions-item>

              <el-descriptions-item>
                <template #label>
                  <el-icon class="align-middle">
                    <Timer />
                  </el-icon>
                  创建日期
                </template>
                {{ userProfile.createTime }}
              </el-descriptions-item>
            </el-descriptions>
          </el-card>
        </div>
      </el-tab-pane>

      <!--账户余额-->
      <el-tab-pane label="账户余额">
        <div class="w-full">
          <el-card>
            <el-row>
              <el-col :span="16">
                <div class="font-bold">账户余额</div>
                <div class="text-14px mt-2">
                  账户余额: {{ userProfile.balance }}
                  <el-button type="primary" plain size="small" class="ml-5"
                    @click="handleOpenDialog(DialogType.RECHARGE)">
                    充值
                  </el-button>
                  <el-button type="success" plain size="small" class="ml-5"
                    @click="handleOpenDialog(DialogType.WITHDRAW)">
                    提现
                  </el-button>
                </div>
              </el-col>
              <el-col :span="16">
                <div class="font-bold mt-5">积分余额</div>
                <div class="text-14px mt-2">
                  积分余额: {{ userProfile.points }}
                  <el-button type="primary" plain size="small" class="ml-5"
                    @click="handleOpenDialog(DialogType.EXCHANGE)">
                    充值
                  </el-button>
                </div>
              </el-col>
            </el-row>
          </el-card>
        </div>
      </el-tab-pane>
      <!-- 安全设置  -->
      <el-tab-pane label="安全设置">
        <el-card>
          <!-- 账户密码 -->
          <el-row>
            <el-col :span="16">
              <div class="font-bold">账户密码</div>
              <div class="text-14px mt-2">
                定期修改密码有助于保护账户安全
                <el-button type="primary" plain size="small" class="ml-5"
                  @click="() => handleOpenDialog(DialogType.PASSWORD)">
                  修改
                </el-button>
              </div>
            </el-col>
          </el-row>
          <!-- 绑定手机 -->
          <!-- <div class="mt-5">
            <div class="font-bold">绑定手机</div>
            <div class="text-14px mt-2">
              <span v-if="userProfile.mobile">已绑定手机号：{{ userProfile.mobile }}</span>
              <span v-else>未绑定手机</span>
              <el-button v-if="userProfile.mobile" type="primary" plain size="small" class="ml-5"
                @click="() => handleOpenDialog(DialogType.MOBILE)">
                更换
              </el-button>
              <el-button v-else type="primary" plain size="small" class="ml-5"
                @click="() => handleOpenDialog(DialogType.MOBILE)">
                绑定
              </el-button>
            </div>
          </div> -->
          <!-- 绑定邮箱 -->
          <!-- <div class="mt-5">
            <div class="font-bold">绑定邮箱</div>
            <div class="text-14px mt-2">
              <span v-if="userProfile.email">已绑定邮箱：{{ userProfile.email }}</span>
              <span v-else>未绑定邮箱</span>
              <el-button v-if="userProfile.email" type="primary" plain size="small" class="ml-5"
                @click="() => handleOpenDialog(DialogType.EMAIL)">
                更换
              </el-button>
              <el-button v-else type="primary" plain size="small" class="ml-5"
                @click="() => handleOpenDialog(DialogType.EMAIL)">
                绑定
              </el-button>
            </div>
          </div> -->
        </el-card>
      </el-tab-pane>
    </el-tabs>

    <!-- 弹窗 -->
    <el-dialog v-model="dialog.visible" :title="dialog.title" width="500" @close="handleCloseDialog()">
      <!-- 账号资料 -->
      <el-form v-if="dialog.type === DialogType.ACCOUNT" ref="userProfileFormRef" :model="userProfileForm"
        :label-width="100">
        <el-form-item label="昵称">
          <el-input v-model="userProfileForm.nickname" />
        </el-form-item>
        <el-form-item label="性别">
          <Dict v-model="userProfileForm.gender" code="gender" />
        </el-form-item>
        <el-form-item label="手机号">
          <el-input v-model="userProfileForm.mobile" />
        </el-form-item>
        <el-form-item label="邮箱">
          <el-input v-model="userProfileForm.email" />
        </el-form-item>
      </el-form>

      <!-- 修改密码 -->
      <el-form v-if="dialog.type === DialogType.PASSWORD" ref="passwordChangeFormRef" :model="passwordChangeForm"
        :rules="passwordChangeRules" :label-width="100">
        <el-form-item label="原密码" prop="oldPassword">
          <el-input v-model="passwordChangeForm.oldPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="新密码" prop="newPassword">
          <el-input v-model="passwordChangeForm.newPassword" type="password" show-password />
        </el-form-item>
        <el-form-item label="确认密码" prop="confirmPassword">
          <el-input v-model="passwordChangeForm.confirmPassword" type="password" show-password />
        </el-form-item>
      </el-form>
      <!-- 绑定手机 -->
      <el-form v-else-if="dialog.type === DialogType.MOBILE" ref="mobileBindingFormRef" :model="mobileUpdateForm"
        :rules="mobileBindingRules" :label-width="100">
        <el-form-item label="手机号码" prop="mobile">
          <el-input v-model="mobileUpdateForm.mobile" style="width: 250px" />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="mobileUpdateForm.code" style="width: 250px">
            <template #append>
              <el-button class="ml-5" :disabled="mobileCountdown > 0" @click="handleSendMobileCode">
                {{ mobileCountdown > 0 ? `${mobileCountdown}s后重新发送` : "发送验证码" }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>

      <!-- 绑定邮箱 -->
      <el-form v-else-if="dialog.type === DialogType.EMAIL" ref="emailBindingFormRef" :model="emailUpdateForm"
        :rules="emailBindingRules" :label-width="100">
        <el-form-item label="邮箱" prop="email">
          <el-input v-model="emailUpdateForm.email" style="width: 250px" />
        </el-form-item>
        <el-form-item label="验证码" prop="code">
          <el-input v-model="emailUpdateForm.code" style="width: 250px">
            <template #append>
              <el-button class="ml-5" :disabled="emailCountdown > 0" @click="handleSendEmailCode">
                {{ emailCountdown > 0 ? `${emailCountdown}s后重新发送` : "发送验证码" }}
              </el-button>
            </template>
          </el-input>
        </el-form-item>
      </el-form>

      <!-- 账号充值 -->
      <el-form v-if="dialog.type === DialogType.RECHARGE && !payData.orderNo" ref="rechargeFormRef"
        :model="rechargeForm" :rules="rechargeRules" :label-width="100">
        <el-form-item label="充值金额" prop="amount">
          <el-input v-model.number="rechargeForm.amount" style="width: 300px" type="number" step="0.01" min="0.01"
            @blur="handleAmountBlur">
            <template #append>
              <span class="unit">RMB</span>
            </template>
          </el-input>
        </el-form-item>

        <el-form-item label="支付方式" prop="payType">
          <el-radio-group v-model="rechargeForm.payType">
            <el-radio label="1" disabled>微信</el-radio>
            <el-radio label="2">支付宝</el-radio>
            <el-radio label="3" disabled>银行卡</el-radio>
          </el-radio-group>
        </el-form-item>

        <div class="recharge-info-box">
          <div class="recharge-info-item">
            <span class="label">当前账户余额：</span>
            <span class="value highlight">{{ userProfile.balance || 0 }} 元</span>
          </div>
          <div class="recharge-info-item">
            <span class="label">充值后余额：</span>
            <span class="value highlight">{{ (userProfile.balance || 0) + (rechargeForm.amount || 0) }} 元</span>
          </div>
        </div>
        <div class="recharge-tips">
          <el-alert title="温馨提示" type="warning" :closable="false" show-icon>
            <template #default>
              <p>1. 充值成功后，资金将立即到账</p>
              <p>2. 如遇支付问题，请联系客服处理</p>
            </template>
          </el-alert>
        </div>
      </el-form>

      <!-- 支付二维码展示 -->
      <div v-if="dialog.type === DialogType.RECHARGE && payData.orderNo" class="pay-container">
        <div class="text-center">
          <h3>请使用支付宝扫码支付</h3>
          <div class="qrcode-wrapper">
            <div v-if="payData.qrCodeContent" class="qrcode-container">
              <qrcode-vue :value="payData.qrCodeContent" :size="200" level="H" class="qrcode" render-as="svg" />
            </div>
            <div v-else class="loading-placeholder">
              <el-icon class="is-loading">
                <Loading />
              </el-icon>
              <span>二维码生成中...</span>
            </div>
          </div>
          <div class="pay-info">
            <p class="mb-2">订单号: {{ payData.orderNo }}</p>
            <p class="mb-3">金额: {{ payData.amount || rechargeForm.amount }} 元</p>
            <div class="btn-group">
              <el-button type="primary" @click="checkPayStatus">我已完成支付</el-button>
              <el-button @click="resetPayForm">取消支付</el-button>
            </div>
          </div>
        </div>
      </div>

      <!--积分充值(人民币==>虚拟币)-->
      <el-form v-if="dialog.type === DialogType.EXCHANGE" ref="exchangeFormRef" :model="rechargeForm"
        :rules="exchangeRules" :label-width="100">
        <el-form-item label="充值积分" prop="amount">
          <el-input v-model.number="rechargeForm.amount" style="width: 300px" type="number" step="0.01" min="0.01"
            @blur="handleAmountBlur" @input="calculateExchangeAmount">
            <template #append>
              <span class="unit">积分</span>
            </template>
          </el-input>
        </el-form-item>

        <div class="exchange-info-box">
          <div class="exchange-info-item">
            <span class="label">当前账户余额：</span>
            <span class="value highlight">{{ userProfile.balance || 0 }} 元</span>
          </div>
          <div class="exchange-info-item">
            <span class="label">消耗金额：</span>
            <span class="value highlight">{{ exchangeAmount }} 元</span>
          </div>
          <div class="exchange-info-item">
            <span class="label">兑换比例：</span>
            <span class="value">1 积分 = 2 元</span>
          </div>
          <div class="exchange-info-item">
            <span class="label">兑换后余额：</span>
            <span class="value" :class="{ 'warning': exchangeAmount > (userProfile.balance || 0) }">
              {{ (userProfile.balance || 0) - exchangeAmount }} 元
            </span>
          </div>
        </div>

        <div class="exchange-tips">
          <el-alert title="温馨提示" type="warning" :closable="false" show-icon>
            <template #default>
              <p>1. 积分兑换后不可逆，请谨慎操作</p>
              <p>2. 账户余额不足时将无法完成兑换</p>
            </template>
          </el-alert>
        </div>
      </el-form>

      <!-- 提现表单 -->
      <el-form v-if="dialog.type === DialogType.WITHDRAW" ref="withdrawFormRef" :model="withdrawForm"
        :rules="withdrawRules" :label-width="100">
        <el-form-item label="支付宝账号" prop="alipayAccount">
          <el-input v-model="withdrawForm.alipayAccount" placeholder="请输入支付宝账号" />
        </el-form-item>
        <el-form-item label="真实姓名" prop="alipayRealName">
          <el-input v-model="withdrawForm.alipayRealName" placeholder="请输入收款人真实姓名" />
        </el-form-item>
        <el-form-item label="提现金额" prop="amount">
          <el-input v-model.number="withdrawForm.amount" style="width: 300px" type="number" step="0.01" min="0.01"
            @blur="handleWithDrawAmountBlur">
            <template #append>
              <span class="unit">RMB</span>
            </template>
          </el-input>
        </el-form-item>

        <div class="recharge-info-box">
          <div class="recharge-info-item">
            <span class="label">当前账户余额：</span>
            <span class="value highlight">{{ userProfile.balance || 0 }} 元</span>
          </div>
          <div class="recharge-info-item">
            <span class="label">提现后余额：</span>
            <span class="value highlight" :class="{ 'warning': withdrawForm.amount > (userProfile.balance || 0) }">{{
              (userProfile.balance || 0) - (withdrawForm.amount || 0) }} 元</span>
          </div>
        </div>
        <div class="withdraw-tips">
          <el-alert title="温馨提示" type="warning" :closable="false" show-icon>
            <template #default>
              <p>1. 提现申请提交后，将在1-3个工作日内处理</p>
              <p>2. 提现金额将直接转入您指定的支付宝账户</p>
              <p>3. 如有疑问，请联系客服</p>
            </template>
          </el-alert>
        </div>
      </el-form>

      <template #footer>
        <span class="dialog-footer">
          <template v-if="dialog.type === DialogType.RECHARGE && payData.orderNo">
            <!-- 支付中状态不显示底部按钮，已在支付区域添加按钮 -->
          </template>
          <template v-else>
            <el-button @click="dialog.visible = false">取消</el-button>
            <el-button type="primary" @click="handleSubmit">确定</el-button>
          </template>
        </span>
      </template>
    </el-dialog>
  </div>
</template>

<script lang="ts" setup>
import UserAPI, {
  UserProfileVO,
  PasswordChangeForm,
  MobileUpdateForm,
  EmailUpdateForm,
  UserProfileForm,
  RechargeForm,
} from "@/api/system/user";

import FileAPI from "@/api/file";
import { useRouter } from "vue-router";
import QrcodeVue from 'qrcode.vue';
import { useNoticeStore } from '@/store/modules/notice';
import { FormInstance, FormRules } from 'element-plus';

import { Camera, Edit, User, Phone, Message, Male, Female, Timer, Loading } from "@element-plus/icons-vue";

const router = useRouter()
const userProfile = ref<UserProfileVO>({});
import { useUserStore } from "@/store";

const userStore = useUserStore();
const { userInfo } = storeToRefs(userStore);

const noticeStore = useNoticeStore();

// 积分兑换金额
const exchangeAmount = ref(0);

// 计算积分兑换金额
const calculateExchangeAmount = () => {
  if (rechargeForm.amount && rechargeForm.amount > 0) {
    exchangeAmount.value = Number((rechargeForm.amount * 2).toFixed(2));
  } else {
    exchangeAmount.value = 0;
  }
};

enum DialogType {
  ACCOUNT = "account",
  PASSWORD = "password",
  MOBILE = "mobile",
  EMAIL = "email",
  RECHARGE = "recharge",
  EXCHANGE = "exchange",
  WITHDRAW = "withdraw"
}

const dialog = reactive({
  visible: false,
  title: "",
  type: "" as DialogType, // 修改账号资料,修改密码、绑定手机、绑定邮箱、充值、提现
});

const userProfileForm = reactive<UserProfileForm>({});
const passwordChangeForm = reactive<PasswordChangeForm>({});
const mobileUpdateForm = reactive<MobileUpdateForm>({});
const emailUpdateForm = reactive<EmailUpdateForm>({});
const rechargeForm = reactive<RechargeForm>({});
const withdrawForm = reactive({
  alipayAccount: '',
  alipayRealName: '',
  amount: 0
})

// 支付数据
const payData = reactive({
  orderNo: '',
  qrCodeContent: '',
  amount: ''
})


// 支付状态检查定时器
const payStatusTimer = ref()

const mobileCountdown = ref(0);
const mobileTimer = ref();

const emailCountdown = ref(0);
const emailTimer = ref();

// 修改密码校验规则
const passwordChangeRules = {
  oldPassword: [{ required: true, message: "请输入原密码", trigger: "blur" }],
  newPassword: [{ required: true, message: "请输入新密码", trigger: "blur" }],
  confirmPassword: [{ required: true, message: "请再次输入新密码", trigger: "blur" }],
};

// 充值金额校验规则
const rechargeRules: FormRules = {
  amount: [
    { required: true, message: "请输入充值金额", trigger: "blur" },
    { type: "number" as const, min: 0.01, message: "充值金额必须大于0", trigger: "blur" },
    { type: "number" as const, max: 10000, message: "单次充值金额不能超过10000元", trigger: "blur" }
  ],
  payType: [
    { required: true, message: "请选择支付方式", trigger: "change" }
  ]
};

// 积分充值校验规则
const exchangeRules: FormRules = {
  amount: [
    { required: true, message: "请输入充值积分", trigger: "blur" },
    { type: "number" as const, min: 0.01, message: "充值积分必须大于0", trigger: "blur" },
    { type: "number" as const, max: 5000, message: "单次充值积分不能超过5000", trigger: "blur" },
    {
      validator: (rule: any, value: number, callback: Function) => {
        if (value && userProfile.value.balance && (value * 2) > userProfile.value.balance) {
          callback(new Error("账户余额不足，无法完成兑换"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
};

// 提现校验规则
const withdrawRules: FormRules = {
  alipayAccount: [
    { required: true, message: "请输入支付宝账号", trigger: "blur" },
  ],
  alipayRealName: [
    { required: true, message: "请输入收款人真实姓名", trigger: "blur" },
  ],
  amount: [
    { required: true, message: "请输入提现金额", trigger: "blur" },
    { type: "number" as const, min: 0.01, message: "提现金额必须大于0", trigger: "blur" },
    {
      validator: (rule: any, value: number, callback: Function) => {
        if (value && userProfile.value.balance && value > userProfile.value.balance) {
          callback(new Error("账户余额不足，无法完成提现"));
        } else {
          callback();
        }
      },
      trigger: "blur"
    }
  ]
};

// 手机号校验规则
const mobileBindingRules = {
  mobile: [
    { required: true, message: "请输入手机号", trigger: "blur" },
    {
      pattern: /^1[3|4|5|6|7|8|9][0-9]\d{8}$/,
      message: "请输入正确的手机号码",
      trigger: "blur",
    },
  ],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
};

// 邮箱校验规则
const emailBindingRules = {
  email: [
    { required: true, message: "请输入邮箱", trigger: "blur" },
    {
      pattern: /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/,
      message: "请输入正确的邮箱地址",
      trigger: "blur",
    },
  ],
  code: [{ required: true, message: "请输入验证码", trigger: "blur" }],
};

/**
 * 打开弹窗
 * @param type 弹窗类型 ACCOUNT: 账号资料 PASSWORD: 修改密码 MOBILE: 绑定手机 EMAIL: 绑定邮箱
 */
const handleOpenDialog = (type: DialogType) => {
  dialog.type = type;
  dialog.visible = true;
  switch (type) {
    case DialogType.ACCOUNT:
      dialog.title = "账号资料";
      // 初始化表单数据
      userProfileForm.id = userProfile.value.id;
      userProfileForm.nickname = userProfile.value.nickname;
      userProfileForm.gender = userProfile.value.gender;
      userProfileForm.mobile = userProfile.value.mobile;
      userProfileForm.email = userProfile.value.email;

      break;
    case DialogType.PASSWORD:
      dialog.title = "修改密码";
      break;
    case DialogType.MOBILE:
      dialog.title = "绑定手机";
      break;
    case DialogType.EMAIL:
      dialog.title = "绑定邮箱";
      break;
    case DialogType.RECHARGE:
      dialog.title = "账号充值";
      break;
    case DialogType.EXCHANGE:
      dialog.title = "积分充值";
      // 重置兑换金额
      exchangeAmount.value = 0;
      break;
  }
};

const handleCloseDialog = () => {
  //重置数据
  dialog.visible = false;
  switch (dialog.type) {
    case DialogType.RECHARGE:
      resetPayForm();
      break;
    case DialogType.EXCHANGE:
      resetPayForm();
      break;
    case DialogType.WITHDRAW:
      resetWithdrawForm();
      break;
  }
}

/**
 * 重置支付表单
 */
const resetPayForm = () => {
  rechargeForm.amount = undefined;
  rechargeForm.payType = undefined;
  payData.orderNo = '';
  payData.qrCodeContent = '';
  payData.amount = '';

  // 清除支付状态检查定时器
  if (payStatusTimer.value) {
    clearInterval(payStatusTimer.value);
    payStatusTimer.value = null;
  }
  //关闭窗口
  dialog.visible = false;
}

// 重置提现表单
const resetWithdrawForm = () => {
  withdrawForm.alipayAccount = '';
  withdrawForm.alipayRealName = '';
  withdrawForm.amount = 0;
}
/**
 * 检查支付状态
 */
const checkPayStatus = async () => {
  if (!payData.orderNo) {
    console.warn('没有有效的订单号，无法查询支付状态');
    return;
  }
  UserAPI.queryPayStatus(payData.orderNo).then(res => {
    if (res === 'TRADE_SUCCESS' || res === 'TRADE_FINISHED') {
      // 清除定时器
      if (payStatusTimer.value) {
        clearInterval(payStatusTimer.value);
        payStatusTimer.value = null;
      }
      // 重新获取通知列表
      noticeStore.fetchNotices();
      // 跳转到支付结果页面
      router.push({
        path: '/payment/result',
        query: {
          status: 'success',
          orderNo: payData.orderNo
        }
      });
      // 重置支付表单
      resetPayForm();
      // 关闭对话框
      handleCloseDialog();
      // 重新加载用户信息
      loadUserProfile();
    } else if (res === 'WAIT_BUYER_PAY') {
      ElMessage.info('订单等待支付，请完成支付');
    } else {
      ElMessage.warning('支付未完成，请检查支付状态');
    }
  }).catch((error) => {
    ElMessage.error('查询支付状态失败');
  });
}
/**
 * 发送手机验证码
 */
function handleSendMobileCode() {
  if (!mobileUpdateForm.mobile) {
    ElMessage.error("请输入手机号");
    return;
  }
  // 验证手机号格式
  const reg = /^1[3-9]\d{9}$/;
  if (!reg.test(mobileUpdateForm.mobile)) {
    ElMessage.error("手机号格式不正确");
    return;
  }
  // 发送短信验证码
  UserAPI.sendMobileCode(mobileUpdateForm.mobile).then(() => {
    ElMessage.success("验证码发送成功");

    // 倒计时 60s 重新发送
    mobileCountdown.value = 60;
    mobileTimer.value = setInterval(() => {
      if (mobileCountdown.value > 0) {
        mobileCountdown.value -= 1;
      } else {
        clearInterval(mobileTimer.value!);
      }
    }, 1000);
  });
}

/**
 * 发送邮箱验证码
 */
function handleSendEmailCode() {
  if (!emailUpdateForm.email) {
    ElMessage.error("请输入邮箱");
    return;
  }
  // 验证邮箱格式
  const reg = /\w[-\w.+]*@([A-Za-z0-9][-A-Za-z0-9]+\.)+[A-Za-z]{2,14}/;
  if (!reg.test(emailUpdateForm.email)) {
    ElMessage.error("邮箱格式不正确");
    return;
  }

  // 发送邮箱验证码
  UserAPI.sendEmailCode(emailUpdateForm.email).then(() => {
    ElMessage.success("验证码发送成功");
    // 倒计时 60s 重新发送
    emailCountdown.value = 60;
    emailTimer.value = setInterval(() => {
      if (emailCountdown.value > 0) {
        emailCountdown.value -= 1;
      } else {
        clearInterval(emailTimer.value!);
      }
    }, 1000);
  });
}

const rechargeFormRef = ref<FormInstance>();
const exchangeFormRef = ref<FormInstance>();
const withdrawFormRef = ref<FormInstance>();

/**
 * 提交表单
 */
const handleSubmit = async () => {
  if (dialog.type === DialogType.ACCOUNT) {
    UserAPI.updateProfile(userProfileForm).then(() => {
      ElMessage.success("账号资料修改成功");
      dialog.visible = false;
      loadUserProfile();
    });
  } else if (dialog.type === DialogType.PASSWORD) {
    if (passwordChangeForm.newPassword !== passwordChangeForm.confirmPassword) {
      ElMessage.error("两次输入的密码不一致");
      return;
    }
    UserAPI.changePassword(passwordChangeForm).then(() => {
      ElMessage.success("密码修改成功");
      dialog.visible = false;
    });
  } else if (dialog.type === DialogType.MOBILE) {
    UserAPI.bindOrChangeMobile(mobileUpdateForm).then(() => {
      ElMessage.success("手机号绑定成功");
      dialog.visible = false;
      loadUserProfile();
    });
  } else if (dialog.type === DialogType.EMAIL) {
    UserAPI.bindOrChangeEmail(emailUpdateForm).then(() => {
      ElMessage.success("邮箱绑定成功");
      dialog.visible = false;
      loadUserProfile();
    });
  } else if (dialog.type === DialogType.RECHARGE) {
    if (!payData.orderNo) {
      // 表单验证
      rechargeFormRef.value?.validate((valid: boolean) => {
        if (valid) {
          // 创建支付订单
          UserAPI.recharge(rechargeForm).then((res) => {
            console.log('支付接口响应：', res);
            if (res) {
              payData.orderNo = res.orderNo;
              payData.qrCodeContent = res.qrCodeContent;
              payData.amount = res.amount;
              console.log('支付二维码内容：', payData.qrCodeContent);

              // 启动定时检查支付状态
              if (payStatusTimer.value) {
                clearInterval(payStatusTimer.value);
              }
              // 每5秒检查一次支付状态
              payStatusTimer.value = setInterval(() => {
                checkPayStatus();
              }, 5000);
            }
          }).catch(error => {
            console.error('创建支付订单失败', error);
            ElMessage.error('创建支付订单失败：' + (error.message || error));
          });
        }
      });
    } else {
      // 已有订单，检查支付状态
      checkPayStatus();
    }
  } else if (dialog.type === DialogType.EXCHANGE) {
    // 表单验证
    exchangeFormRef.value?.validate((valid: boolean) => {
      if (valid) {
        UserAPI.rechargeExchange(rechargeForm).then((res) => {
          if (res) {
            ElMessage.success("积分充值成功");
            // 重新获取通知列表
            noticeStore.fetchNotices();
            loadUserProfile();
          } else {
            ElMessage.error("积分充值失败");
          }
          dialog.visible = false;
        });
      }
    });
  } else if (dialog.type === DialogType.WITHDRAW) {
    // 表单验证
    withdrawFormRef.value?.validate((valid: boolean) => {
      if (valid) {
        UserAPI.withdraw(withdrawForm.alipayAccount, withdrawForm.alipayRealName, withdrawForm.amount).then((res) => {
          if (res) {
            ElMessage.success("提现申请已提交");
          }
          resetWithdrawForm();
          loadUserProfile();
          dialog.visible = false;
        })
      }
    })
  }
};

const fileInput = ref<HTMLInputElement | null>(null);

const triggerFileUpload = () => {
  fileInput.value?.click();
};

const handleFileChange = async (event: Event) => {
  const target = event.target as HTMLInputElement;
  const file = target.files ? target.files[0] : null;
  if (file) {
    // 调用文件上传API
    try {
      const data = await FileAPI.uploadFile(file);
      // 更新用户头像
      userProfile.value.avatar = data.url;
      // 更新用户信息
      await UserAPI.updateProfile({
        avatar: data.url,
      });
      //更新浏览器中的头像
      userInfo.value.avatar = data.url;
    } catch (error) {
      console.error("头像上传失败：" + error);
      ElMessage.error("头像上传失败");
    }
  }
};

/** 加载用户信息 */
const loadUserProfile = async () => {
  const data = await UserAPI.getProfile();
  userProfile.value = data;
};

// 输入框失去焦点时，格式化金额
const handleAmountBlur = (event: any) => {
  let value = parseFloat(event.target.value);
  if (isNaN(value)) {
    value = 0.00;
  }
  // 四舍五入并保留两位小数
  rechargeForm.amount = Number(value.toFixed(2));
};
// 输入框失去焦点时，格式化金额
const handleWithDrawAmountBlur = (event: any) => {
  let value = parseFloat(event.target.value);
  if (isNaN(value)) {
    value = 0.00;
  }
  // 四舍五入并保留两位小数
  withdrawForm.amount = Number(value.toFixed(2));
};

onMounted(async () => {
  if (mobileTimer.value) {
    clearInterval(mobileTimer.value);
  }
  if (emailTimer.value) {
    clearInterval(emailTimer.value);
  }
  await loadUserProfile();
});
</script>

<style lang="scss" scoped>
/** 关闭tag标签  */
.app-container {
  /* 50px = navbar = 50px */
  height: calc(100vh - 50px);
  background: var(--el-fill-color-blank);
}

/** 开启tag标签  */
.hasTagsView {
  .app-container {
    /* 84px = navbar + tags-view = 50px + 34px */
    height: calc(100vh - 84px);
  }
}

/* 支付相关样式 */
.pay-container {
  padding: 10px;
  text-align: center;
}

.qrcode-wrapper {
  margin: 15px auto;
  width: 220px;
  height: 220px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: #fff;
  border-radius: 8px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
}

.text-center {
  text-align: center;
}

.loading-placeholder {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  height: 100%;
}

.qrcode {
  margin: 0;
  padding: 0;
}

.pay-info {
  margin-top: 15px;
  text-align: center;
}

.pay-info p {
  margin: 5px 0;
}

.btn-group {
  margin-top: 15px;
  display: flex;
  justify-content: center;
  gap: 10px;
}

.qrcode-container {
  padding: 10px;
  background-color: #fff;
  border-radius: 4px;
}

/* 积分兑换相关样式 */
.exchange-info-box {
  margin: 15px 0;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

.exchange-info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;

  &:last-child {
    margin-bottom: 0;
  }

  .label {
    color: #606266;
  }

  .value {
    font-weight: 500;

    &.highlight {
      color: #409EFF;
      font-weight: bold;
    }

    &.warning {
      color: #F56C6C;
    }
  }
}

.exchange-tips {
  margin-top: 15px;

  :deep(.el-alert) {
    padding: 10px 15px;

    .el-alert__title {
      font-weight: bold;
    }

    p {
      margin: 5px 0;
      font-size: 13px;
    }
  }
}

/* 余额充值相关样式 */
.recharge-info-box {
  margin: 15px 0;
  padding: 15px;
  background-color: #f8f9fa;
  border-radius: 8px;
  border: 1px solid #ebeef5;
}

.recharge-info-item {
  display: flex;
  justify-content: space-between;
  margin-bottom: 10px;
  font-size: 14px;

  &:last-child {
    margin-bottom: 0;
  }

  .label {
    color: #606266;
  }

  .value {
    font-weight: 500;

    &.highlight {
      color: #409EFF;
      font-weight: bold;
    }
  }
}

.recharge-tips {
  margin-top: 15px;

  :deep(.el-alert) {
    padding: 10px 15px;

    .el-alert__title {
      font-weight: bold;
    }

    p {
      margin: 5px 0;
      font-size: 13px;
    }
  }
}
</style>
